<template>
  <div id="competitionCenterView">
    <h2 class="page-title">竞赛中心</h2>
    
    <!-- 统计信息卡片 -->
    <div class="statistics-container">
      <a-row :gutter="16">
        <a-col :span="8">
          <a-card class="statistic-card">
            <div class="statistic-content">
              <icon-calendar-clock class="statistic-icon upcoming" />
              <div class="statistic-info">
                <div class="statistic-value">{{ getCompetitionCountByStatus(0) }}</div>
                <div class="statistic-label">即将开始的竞赛</div>
              </div>
            </div>
            <div ref="upcomingChart" class="chart-container"></div>
          </a-card>
        </a-col>
        <a-col :span="8">
          <a-card class="statistic-card">
            <div class="statistic-content">
              <icon-fire class="statistic-icon ongoing" />
              <div class="statistic-info">
                <div class="statistic-value">{{ getCompetitionCountByStatus(1) }}</div>
                <div class="statistic-label">正在进行的竞赛</div>
              </div>
            </div>
            <div ref="ongoingChart" class="chart-container"></div>
          </a-card>
        </a-col>
        <a-col :span="8">
          <a-card class="statistic-card">
            <div class="statistic-content">
              <icon-user-group class="statistic-icon total" />
              <div class="statistic-info">
                <div class="statistic-value">{{ getTotalRegistrations() }}</div>
                <div class="statistic-label">总报名人数</div>
              </div>
            </div>
            <div ref="registrationChart" class="chart-container"></div>
          </a-card>
        </a-col>
      </a-row>
    </div>
    
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-header">
        <h3 class="search-title">查找竞赛</h3>
        <div v-if="isAdmin" class="admin-actions">
          <a-button type="primary" status="success" @click="showAddModal()">
            <template #icon>
              <icon-plus />
            </template>
            新增竞赛
          </a-button>
        </div>
      </div>
      <a-form :model="searchParams" layout="horizontal">
        <a-row :gutter="16">
          <a-col :xs="24" :sm="12" :md="8" :lg="8">
            <a-form-item field="title" label="竞赛标题">
              <a-input
                v-model="searchParams.title"
                placeholder="请输入竞赛标题"
                allow-clear
              >
                <template #prefix>
                  <icon-search />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="12" :md="8" :lg="8">
            <a-form-item field="status" label="竞赛状态">
              <a-select
                v-model="searchParams.status"
                placeholder="请选择状态"
                allow-clear
              >
                <a-option :value="0">未开始</a-option>
                <a-option :value="1">进行中</a-option>
                <a-option :value="2">已结束</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="8" :lg="8" class="search-actions">
            <a-form-item>
              <a-button type="primary" @click="loadData()" class="search-btn">
                <template #icon>
                  <icon-search />
                </template>
                搜索
              </a-button>
              <a-button @click="resetSearch()" class="reset-btn">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 竞赛列表 -->
    <div class="competition-grid">
      <a-spin :loading="loading">
        <a-empty v-if="dataList.length === 0" description="暂无竞赛" />
        <div v-else class="competition-cards">
          <a-card
            v-for="item in dataList"
            :key="item.id"
            class="competition-card"
            :hoverable="true"
          >
            <div class="card-header">
              <h3 class="competition-title">{{ item.title }}</h3>
              <a-tag :color="getStatusColor(item.status)">{{ getStatusText(item.status) }}</a-tag>
            </div>
            <div class="card-content">
              <p class="competition-description">{{ item.description }}</p>
              <div class="competition-info">
                <p><icon-calendar /> 开始时间: {{ formatDateTime(item.startTime) }}</p>
                <p><icon-calendar /> 结束时间: {{ formatDateTime(item.endTime) }}</p>
                <p><icon-user /> 当前报名人数: {{ item.registrationCount || 0 }}</p>
              </div>
              <div class="registration-info" v-if="item.isRegistered">
                <a-tag color="green">已报名</a-tag>
              </div>
            </div>
            <div class="card-actions">
              <a-button
                v-if="!item.isRegistered && (item.status === 0 || item.status === 1)"
                type="primary"
                @click="handleRegister(item)"
              >
                <template #icon><icon-user-add /></template>
                立即报名
              </a-button>
              <a-button
                v-if="item.isRegistered"
                status="danger"
                @click="handleCancelRegistration(item)"
              >
                <template #icon><icon-close /></template>
                取消报名
              </a-button>
              <a-button v-if="item.status === 1 && item.isRegistered" type="outline" status="success">
                <template #icon><icon-play-arrow /></template>
                进入竞赛
              </a-button>
              <a-button v-if="isAdmin" type="outline" @click="showRegistrations(item)">
                <template #icon><icon-file /></template>
                报名记录
              </a-button>
              <a-button v-if="isAdmin" type="outline" status="warning" @click="showEditModal(item)">
                <template #icon><icon-edit /></template>
                编辑
              </a-button>
              <a-button v-if="isAdmin" type="outline" status="danger" @click="handleDelete(item)">
                <template #icon><icon-delete /></template>
                删除
              </a-button>
            </div>
          </a-card>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <a-pagination
            :total="total"
            :current="searchParams.current"
            :page-size="searchParams.pageSize"
            @change="handlePageChange"
            show-total
          />
        </div>
      </a-spin>
    </div>

    <!-- 竞赛表单对话框 -->
    <a-modal
      v-model:visible="competitionModalVisible"
      :title="isEdit ? '编辑竞赛' : '新增竞赛'"
      @ok="handleSaveCompetition"
      @cancel="competitionModalVisible = false"
      :ok-button-props="{ loading: submitting }"
      width="650px"
    >
      <a-form
        ref="competitionForm"
        :model="competitionForm"
        label-align="right"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-form-item field="title" label="竞赛标题" required>
          <a-input v-model="competitionForm.title" placeholder="请输入竞赛标题" allow-clear />
        </a-form-item>
        <a-form-item field="description" label="竞赛描述" required>
          <a-textarea
            v-model="competitionForm.description"
            placeholder="请输入竞赛描述"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>
        <a-form-item field="startTime" label="开始时间" required>
          <a-date-picker
            v-model="competitionForm.startTime"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始时间"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item field="endTime" label="结束时间" required>
          <a-date-picker
            v-model="competitionForm.endTime"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择结束时间"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item field="status" label="竞赛状态" required>
          <a-select v-model="competitionForm.status" placeholder="请选择状态">
            <a-option :value="0">未开始</a-option>
            <a-option :value="1">进行中</a-option>
            <a-option :value="2">已结束</a-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="isEdit" field="registrationCount" label="报名人数">
          <a-input-number
            v-model="competitionForm.registrationCount"
            placeholder="报名人数"
            :min="0"
            :disabled="true"
            style="width: 100%"
          />
          <div class="form-item-tip">报名人数不可直接修改</div>
        </a-form-item>
        <a-form-item v-if="isEdit" field="createTime" label="创建时间">
          <a-input
            :model-value="formatDateTime(competitionForm.createTime)"
            :disabled="true"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 报名记录抽屉 -->
    <a-drawer
      v-model:visible="registrationsDrawerVisible"
      title="报名记录"
      width="650px"
      @cancel="registrationsDrawerVisible = false"
    >
      <div class="registration-drawer-header">
        <h3 v-if="currentCompetition">{{ currentCompetition.title }}</h3>
        <p v-if="currentCompetition">
          报名情况: {{ currentCompetition.registrationCount || 0 }}
        </p>
      </div>
      
      <a-spin :loading="registrationsLoading">
        <a-empty 
          v-if="registrations.length === 0" 
          description="暂无报名记录" 
        />
        <a-table 
          v-else
          :data="registrations" 
          :pagination="false"
        >
          <a-table-column title="用户ID" data-index="userId" />
          <a-table-column title="用户名" data-index="username" />
          <a-table-column title="报名时间" data-index="createTime">
            <template #cell="{ record }">
              {{ formatDateTime(record.createTime) }}
            </template>
          </a-table-column>
          <a-table-column title="状态" data-index="isDelete">
            <template #cell="{ record }">
              <a-tag :color="record.isDelete === 0 ? 'green' : 'red'">
                {{ record.isDelete === 0 ? '有效' : '已取消' }}
              </a-tag>
            </template>
          </a-table-column>
        </a-table>
      </a-spin>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, onUnmounted } from 'vue';
import {
  Message,
  Modal
} from '@arco-design/web-vue';
import moment from 'moment';
import { useStore } from 'vuex';
import * as echarts from 'echarts';

// 模拟数据接口
interface Competition {
  id: string;
  title: string;
  description: string;
  startTime: Date;
  endTime: Date;
  status: number; // 0-未开始 1-进行中 2-已结束
  registrationCount: number;
  userId: string;
  createTime: Date;
  updateTime: Date;
  isRegistered?: boolean;
}

interface CompetitionRegistration {
  id: string;
  competitionId: string;
  userId: string;
  username: string;
  createTime: Date;
  updateTime: Date;
  isDelete: number;
}

const store = useStore();

// 判断是否为管理员
const isAdmin = computed(() => {
  return store.state.user?.loginUser?.userRole === 'admin';
});

const loading = ref(false);
const registrationsLoading = ref(false);
const submitting = ref(false);
const competitionModalVisible = ref(false);
const registrationsDrawerVisible = ref(false);
const isEdit = ref(false);
const currentCompetition = ref<Competition | null>(null);
const registrations = ref<CompetitionRegistration[]>([]);
const dataList = ref<Competition[]>([]);
const total = ref(0);
const searchParams = reactive({
  current: 1,
  pageSize: 10,
  title: '',
  status: undefined,
});
const myRegistrations = ref<Set<string>>(new Set());

// 竞赛表单数据
const competitionForm = ref<Competition>({
  id: '',
  title: '',
  description: '',
  startTime: new Date(),
  endTime: new Date(),
  status: 0,
  registrationCount: 0,
  userId: store.state.user?.loginUser?.id || '1',
  createTime: new Date(),
  updateTime: new Date()
});

// 模拟竞赛数据
const mockCompetitions: Competition[] = [
  {
    id: '1',
    title: '算法竞赛2025',
    description: '这是一个算法竞赛，主要考察参赛者的算法设计和编程能力。包含多道算法题目，涵盖数据结构、动态规划、图论等多个方面。',
    startTime: new Date('2025-05-10T10:00:00'),
    endTime: new Date('2025-05-10T14:00:00'),
    status: 0,
    registrationCount: 42,
    userId: 'admin',
    createTime: new Date('2025-04-01T08:30:00'),
    updateTime: new Date('2025-04-01T08:30:00')
  },
  {
    id: '2',
    title: 'Web开发挑战赛',
    description: '前端与后端结合的全栈开发竞赛，参赛者需要在规定时间内完成一个小型Web应用的开发，包括前端界面和后端API。',
    startTime: new Date('2025-05-05T09:00:00'),
    endTime: new Date('2025-05-05T17:00:00'),
    status: 1,
    registrationCount: 38,
    userId: 'admin',
    createTime: new Date('2025-04-02T10:15:00'),
    updateTime: new Date('2025-04-02T10:15:00')
  },
  {
    id: '3',
    title: '人工智能创新大赛',
    description: '探索AI领域的创新应用，参赛者需要利用机器学习、深度学习等技术解决实际问题，并提交解决方案和演示。',
    startTime: new Date('2025-04-20T13:00:00'),
    endTime: new Date('2025-04-25T13:00:00'),
    status: 2,
    registrationCount: 56,
    userId: 'admin',
    createTime: new Date('2025-03-15T14:20:00'),
    updateTime: new Date('2025-03-15T14:20:00')
  }
];

// 模拟报名记录
const mockRegistrations: Record<string, CompetitionRegistration[]> = {
  '1': [
    {
      id: '101',
      competitionId: '1',
      userId: 'user1',
      username: '张三',
      createTime: new Date('2025-04-15T09:30:00'),
      updateTime: new Date('2025-04-15T09:30:00'),
      isDelete: 0
    },
    {
      id: '102',
      competitionId: '1',
      userId: 'user2',
      username: '李四',
      createTime: new Date('2025-04-16T14:20:00'),
      updateTime: new Date('2025-04-16T14:20:00'),
      isDelete: 0
    }
  ],
  '2': [
    {
      id: '201',
      competitionId: '2',
      userId: 'user1',
      username: '张三',
      createTime: new Date('2025-04-10T11:45:00'),
      updateTime: new Date('2025-04-10T11:45:00'),
      isDelete: 0
    },
    {
      id: '202',
      competitionId: '2',
      userId: 'user3',
      username: '王五',
      createTime: new Date('2025-04-12T16:30:00'),
      updateTime: new Date('2025-04-12T16:30:00'),
      isDelete: 0
    }
  ],
  '3': [
    {
      id: '301',
      competitionId: '3',
      userId: 'user2',
      username: '李四',
      createTime: new Date('2025-03-25T10:10:00'),
      updateTime: new Date('2025-03-25T10:10:00'),
      isDelete: 0
    },
    {
      id: '302',
      competitionId: '3',
      userId: 'user3',
      username: '王五',
      createTime: new Date('2025-03-26T13:50:00'),
      updateTime: new Date('2025-03-26T13:50:00'),
      isDelete: 1
    }
  ]
};

// 图表引用
const upcomingChart = ref<HTMLElement | null>(null);
const ongoingChart = ref<HTMLElement | null>(null);
const registrationChart = ref<HTMLElement | null>(null);

// 图表实例
let upcomingChartInstance: echarts.ECharts | null = null;
let ongoingChartInstance: echarts.ECharts | null = null;
let registrationChartInstance: echarts.ECharts | null = null;

// 获取竞赛列表
const loadData = async () => {
  loading.value = true;
  try {
    // 模拟API调用
    setTimeout(() => {
      const filteredData = mockCompetitions.filter(item => {
        // 标题过滤
        if (searchParams.title && !item.title.includes(searchParams.title)) {
          return false;
        }
        // 状态过滤
        if (searchParams.status !== undefined && item.status !== searchParams.status) {
          return false;
        }
        return true;
      });
      
      dataList.value = filteredData.map(item => ({
        ...item,
        isRegistered: myRegistrations.value.has(item.id)
      }));
      total.value = filteredData.length;
      loading.value = false;
    }, 500);
  } catch (error) {
    console.error('获取竞赛列表失败', error);
    Message.error('获取竞赛列表失败');
    loading.value = false;
  }
};

// 加载用户已报名的竞赛
const loadMyRegistrations = async () => {
  try {
    // 模拟API调用
    setTimeout(() => {
      // 假设用户ID为user1
      const userId = store.state.user?.loginUser?.id || 'user1';
      const registeredIds = new Set<string>();
      
      // 遍历所有竞赛的报名记录
      Object.entries(mockRegistrations).forEach(([competitionId, registrations]) => {
        // 查找当前用户的有效报名记录
        const hasRegistered = registrations.some(reg => 
          reg.userId === userId && reg.isDelete === 0
        );
        if (hasRegistered) {
          registeredIds.add(competitionId);
        }
      });
      
      myRegistrations.value = registeredIds;
      
      // 更新竞赛列表中的报名状态
      dataList.value = dataList.value.map(comp => ({
        ...comp,
        isRegistered: registeredIds.has(comp.id)
      }));
    }, 300);
  } catch (error) {
    console.error('获取我的报名记录失败', error);
  }
};

// 处理分页改变
const handlePageChange = (page: number) => {
  searchParams.current = page;
  loadData();
};

// 显示新增对话框
const showAddModal = () => {
  isEdit.value = false;
  competitionForm.value = {
    id: '',
    title: '',
    description: '',
    startTime: new Date(),
    endTime: moment().add(7, 'days').toDate(),
    status: 0,
    registrationCount: 0,
    userId: store.state.user?.loginUser?.id || 'admin',
    createTime: new Date(),
    updateTime: new Date()
  };
  competitionModalVisible.value = true;
};

// 显示编辑对话框
const showEditModal = (record: Competition) => {
  isEdit.value = true;
  // 确保日期对象正确转换
  const startTime = typeof record.startTime === 'string' ? new Date(record.startTime) : record.startTime;
  const endTime = typeof record.endTime === 'string' ? new Date(record.endTime) : record.endTime;
  
  // 深拷贝竞赛数据到表单
  competitionForm.value = {
    id: record.id,
    title: record.title,
    description: record.description,
    startTime: startTime,
    endTime: endTime,
    status: record.status,
    registrationCount: record.registrationCount,
    userId: record.userId,
    createTime: record.createTime,
    updateTime: new Date() // 更新时间设为当前时间
  };
  
  competitionModalVisible.value = true;
};

// 保存竞赛信息
const handleSaveCompetition = async () => {
  submitting.value = true;
  try {
    // 模拟API调用
    setTimeout(() => {
      if (isEdit.value) {
        // 编辑竞赛
        const index = mockCompetitions.findIndex(item => item.id === competitionForm.value.id);
        if (index !== -1) {
          mockCompetitions[index] = {
            ...competitionForm.value,
            updateTime: new Date()
          };
          Message.success('竞赛更新成功');
        }
      } else {
        // 新增竞赛
        const newCompetition: Competition = {
          ...competitionForm.value,
          id: String(mockCompetitions.length + 1),
          registrationCount: 0,
          createTime: new Date(),
          updateTime: new Date()
        };
        mockCompetitions.push(newCompetition);
        Message.success('竞赛添加成功');
      }
      competitionModalVisible.value = false;
      loadData();
      submitting.value = false;
    }, 500);
  } catch (error) {
    console.error('保存竞赛失败', error);
    Message.error('保存失败，请稍后重试');
    submitting.value = false;
  }
};

// 删除竞赛
const handleDelete = (record: Competition) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除竞赛"${record.title}"吗？`,
    onOk: () => {
      // 模拟API调用
      setTimeout(() => {
        const index = mockCompetitions.findIndex(item => item.id === record.id);
        if (index !== -1) {
          mockCompetitions.splice(index, 1);
          Message.success('竞赛删除成功');
          loadData();
        }
      }, 500);
    }
  });
};

// 查看报名记录
const showRegistrations = (competition: Competition) => {
  currentCompetition.value = competition;
  registrationsDrawerVisible.value = true;
  loadRegistrations(competition.id);
};

// 加载报名记录
const loadRegistrations = async (competitionId: string) => {
  registrationsLoading.value = true;
  try {
    // 模拟API调用
    setTimeout(() => {
      registrations.value = mockRegistrations[competitionId] || [];
      registrationsLoading.value = false;
    }, 500);
  } catch (error) {
    console.error('获取报名记录失败', error);
    Message.error('获取报名记录失败');
    registrationsLoading.value = false;
  }
};

// 报名竞赛
const handleRegister = async (competition: Competition) => {
  loading.value = true;
  try {
    // 模拟API调用
    setTimeout(() => {
      const userId = store.state.user?.loginUser?.id || 'user1';
      const username = store.state.user?.loginUser?.userName || '当前用户';
      
      // 创建新的报名记录
      const newRegistration: CompetitionRegistration = {
        id: `${Date.now()}`,
        competitionId: competition.id,
        userId,
        username,
        createTime: new Date(),
        updateTime: new Date(),
        isDelete: 0
      };
      
      // 添加到报名记录中
      if (!mockRegistrations[competition.id]) {
        mockRegistrations[competition.id] = [];
      }
      mockRegistrations[competition.id].push(newRegistration);
      
      // 更新竞赛报名人数
      const index = mockCompetitions.findIndex(item => item.id === competition.id);
      if (index !== -1) {
        mockCompetitions[index].registrationCount += 1;
      }
      
      Message.success('报名成功');
      // 更新报名状态
      loadMyRegistrations();
      loadData();
      loading.value = false;
    }, 500);
  } catch (error) {
    console.error('报名失败', error);
    Message.error('报名失败，请稍后重试');
    loading.value = false;
  }
};

// 取消报名
const handleCancelRegistration = async (competition: Competition) => {
  loading.value = true;
  try {
    // 模拟API调用
    setTimeout(() => {
      const userId = store.state.user?.loginUser?.id || 'user1';
      
      // 找到用户的报名记录并标记为已取消
      const registrations = mockRegistrations[competition.id] || [];
      const registrationIndex = registrations.findIndex(
        reg => 
          reg.userId === userId && reg.isDelete === 0
      );
      
      if (registrationIndex !== -1) {
        registrations[registrationIndex].isDelete = 1;
        registrations[registrationIndex].updateTime = new Date();
        
        // 更新竞赛报名人数
        const competitionIndex = mockCompetitions.findIndex(item => item.id === competition.id);
        if (competitionIndex !== -1 && mockCompetitions[competitionIndex].registrationCount > 0) {
          mockCompetitions[competitionIndex].registrationCount -= 1;
        }
        
        Message.success('取消报名成功');
      }
      
      // 更新报名状态
      loadMyRegistrations();
      loadData();
      loading.value = false;
    }, 500);
  } catch (error) {
    console.error('取消报名失败', error);
    Message.error('取消报名失败，请稍后重试');
    loading.value = false;
  }
};

// 获取状态文本
const getStatusText = (status: number): string => {
  switch (status) {
    case 0:
      return '未开始';
    case 1:
      return '进行中';
    case 2:
      return '已结束';
    default:
      return '未知状态';
  }
};

// 获取状态颜色
const getStatusColor = (status: number): string => {
  switch (status) {
    case 0:
      return 'blue';
    case 1:
      return 'green';
    case 2:
      return 'red';
    default:
      return 'gray';
  }
};

// 格式化日期时间
const formatDateTime = (dateTime: Date | string): string => {
  if (!dateTime) return '';
  return moment(dateTime).format('YYYY-MM-DD HH:mm:ss');
};

// 初始化图表
const initCharts = () => {
  // 即将开始的竞赛图表
  if (upcomingChart.value) {
    upcomingChartInstance = echarts.init(upcomingChart.value);
    const upcomingOption = {
      color: ['#165DFF'],
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['本周', '下周', '本月'],
        axisLine: {
          lineStyle: {
            color: '#86909C'
          }
        },
        axisLabel: {
          color: '#86909C'
        }
      },
      yAxis: {
        type: 'value',
        minInterval: 1,
        axisLine: {
          show: false
        },
        axisLabel: {
          color: '#86909C'
        },
        splitLine: {
          lineStyle: {
            color: '#E5E6EB'
          }
        }
      },
      series: [
        {
          name: '即将开始',
          type: 'bar',
          barWidth: '40%',
          data: [
            getCompetitionCountByStatus(0), 
            Math.round(getCompetitionCountByStatus(0) * 0.7), 
            Math.round(getCompetitionCountByStatus(0) * 1.5)
          ],
          itemStyle: {
            borderRadius: [4, 4, 0, 0]
          }
        }
      ],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      }
    };
    upcomingChartInstance.setOption(upcomingOption);
  }

  // 正在进行的竞赛图表
  if (ongoingChart.value) {
    ongoingChartInstance = echarts.init(ongoingChart.value);
    const ongoingOption = {
      color: ['#41B883', '#165DFF', '#F53F3F'],
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: ['进行中', '未开始', '已结束']
      },
      series: [
        {
          name: '竞赛状态',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}: {c}'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: true
          },
          data: [
            { value: getCompetitionCountByStatus(1), name: '进行中' },
            { value: getCompetitionCountByStatus(0), name: '未开始' },
            { value: getCompetitionCountByStatus(2), name: '已结束' }
          ]
        }
      ]
    };
    ongoingChartInstance.setOption(ongoingOption);
  }

  // 报名人数图表
  if (registrationChart.value) {
    registrationChartInstance = echarts.init(registrationChart.value);
    
    // 获取每个竞赛的报名人数数据
    const competitionNames = mockCompetitions.map(comp => comp.title.substring(0, 4) + '...');
    const registrationData = mockCompetitions.map(comp => comp.registrationCount);
    
    const registrationOption = {
      color: ['#F7DC6F'],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: '#86909C',
            width: 1,
            type: 'solid'
          }
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: competitionNames,
        axisLine: {
          lineStyle: {
            color: '#86909C'
          }
        },
        axisLabel: {
          color: '#86909C'
        }
      },
      yAxis: {
        type: 'value',
        minInterval: 1,
        axisLine: {
          show: false
        },
        axisLabel: {
          color: '#86909C'
        },
        splitLine: {
          lineStyle: {
            color: '#E5E6EB'
          }
        }
      },
      series: [
        {
          name: '报名人数',
          type: 'line',
          stack: 'Total',
          smooth: true,
          lineStyle: {
            width: 3,
            shadowColor: 'rgba(0,0,0,0.2)',
            shadowBlur: 10,
            shadowOffsetY: 10
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(247, 220, 111, 0.8)'
              },
              {
                offset: 1,
                color: 'rgba(247, 220, 111, 0.1)'
              }
            ])
          },
          emphasis: {
            focus: 'series'
          },
          data: registrationData
        }
      ]
    };
    registrationChartInstance.setOption(registrationOption);
  }
};

// 窗口大小改变时重新调整图表大小
const resizeCharts = () => {
  upcomingChartInstance?.resize();
  ongoingChartInstance?.resize();
  registrationChartInstance?.resize();
};

// 页面加载时获取数据
onMounted(() => {
  loadData();
  loadMyRegistrations();
  
  // 初始化图表
  setTimeout(() => {
    initCharts();
    window.addEventListener('resize', resizeCharts);
  }, 300);
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', resizeCharts);
  upcomingChartInstance?.dispose();
  ongoingChartInstance?.dispose();
  registrationChartInstance?.dispose();
});

// 重置搜索
const resetSearch = () => {
  searchParams.title = '';
  searchParams.status = undefined;
  loadData();
};

// 获取竞赛数量
const getCompetitionCountByStatus = (status: number): number => {
  return mockCompetitions.filter(item => item.status === status).length;
};

// 获取总报名人数
const getTotalRegistrations = (): number => {
  return mockCompetitions.reduce((total, competition) => total + competition.registrationCount, 0);
};
</script>

<style scoped>
.page-title {
  margin-bottom: 24px;
  font-size: 28px;
  font-weight: 600;
  color: var(--color-text-1);
  position: relative;
  padding-left: 16px;
  display: inline-block;
}

.page-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 10%;
  height: 80%;
  width: 4px;
  background: linear-gradient(to bottom, #165DFF, #41B883);
  border-radius: 2px;
}

.statistics-container {
  margin-bottom: 24px;
  padding: 20px;
  background-color: var(--color-bg-2);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.statistic-card {
  height: 100%;
  min-height: 380px; /* 增加最小高度 */
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

.statistic-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.statistic-content {
  display: flex;
  align-items: center;
  padding: 16px;
}

.statistic-icon {
  font-size: 24px;
  margin-right: 16px;
}

.statistic-icon.upcoming {
  color: #165DFF;
}

.statistic-icon.ongoing {
  color: #41B883;
}

.statistic-icon.total {
  color: #F7DC6F;
}

.statistic-info {
  flex: 1;
}

.statistic-value {
  font-size: 24px;
  font-weight: 600;
  color: var(--color-text-1);
}

.statistic-label {
  font-size: 14px;
  color: var(--color-text-3);
}

.chart-container {
  height: 200px;
  padding: 16px;
  background-color: var(--color-fill-2);
  border-radius: 8px;
}

.search-container {
  margin-bottom: 24px;
  padding: 20px;
  background-color: var(--color-bg-2);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.search-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-1);
}

.admin-actions {
  display: flex;
  justify-content: flex-end;
}

.competition-grid {
  margin-bottom: 32px;
}

.competition-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
  gap: 24px;
}

.competition-card {
  height: 100%;
  min-height: 380px; /* 增加最小高度 */
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

.competition-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--color-border-2);
}

.competition-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--color-text-1);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 75%;
}

.card-content {
  flex: 1;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
}

.competition-description {
  font-size: 14px;
  color: var(--color-text-2);
  margin-bottom: 20px;
  display: -webkit-box;
  overflow: hidden;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2; /* 标准属性，增加兼容性 */
  line-height: 1.6;
  max-height: 3.2em;
}

.competition-info {
  font-size: 14px;
  color: var(--color-text-3);
  background-color: var(--color-fill-2);
  padding: 12px;
  border-radius: 6px;
  margin-top: auto; /* 将信息区域推到底部 */
}

.competition-info p {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.competition-info p:last-child {
  margin-bottom: 0;
}

.competition-info p i {
  margin-right: 10px;
  color: var(--color-primary-light-4);
}

.registration-info {
  margin-top: 12px;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  flex-wrap: wrap; /* 允许按钮换行 */
  gap: 8px; /* 按钮之间的间距 */
  padding-top: 16px;
  margin-top: auto;
  border-top: 1px solid var(--color-border-2);
}

.card-actions :deep(.arco-btn) {
  margin-right: 8px;
  margin-bottom: 8px;
  min-width: 90px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s ease;
}

.card-actions :deep(.arco-btn:last-child) {
  margin-right: 0;
}

.card-actions :deep(.arco-btn:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.card-actions :deep(.arco-btn-primary) {
  font-weight: 600;
  padding: 0 16px;
}

.card-actions :deep(.arco-btn[status="danger"]) {
  font-weight: 600;
}

.card-actions :deep(.arco-btn[status="success"]) {
  font-weight: 600;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

.registration-drawer-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--color-border-2);
}

.registration-drawer-header h3 {
  margin-bottom: 8px;
  font-size: 20px;
  font-weight: 600;
  color: var(--color-text-1);
}

/* 状态标签样式 */
:deep(.arco-tag) {
  font-weight: 500;
  padding: 2px 10px;
  border-radius: 4px;
}

/* 按钮样式优化 */
:deep(.arco-btn) {
  font-weight: 500;
  border-radius: 4px;
}

/* 表格样式优化 */
:deep(.arco-table-th) {
  background-color: var(--color-fill-2);
  font-weight: 600;
}

:deep(.arco-table-tr:hover) {
  background-color: var(--color-fill-1);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .competition-cards {
    grid-template-columns: 1fr;
  }
  
  .search-container {
    padding: 16px;
  }
  
  .page-title {
    font-size: 24px;
  }
}

.search-actions {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
}

.search-actions .arco-form-item {
  margin-bottom: 0;
  width: 100%;
  display: flex;
  justify-content: flex-end;
}

.search-btn {
  margin-right: 10px;
  min-width: 90px;
}

.reset-btn {
  min-width: 90px;
}
</style>
